const querystring = require('querystring')
const redis = require('./src/db/redis')
const { accessLog } = require('./src/utils/log')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')


// 获取 cookie 的过期时间
const getCookieExpires = () => {
  const d = new Date()
  d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
  console.log('d.toGMTString() is ', d.toGMTString())
  return d.toGMTString()
}

// 处理POST数据
const getPostData = (req) => {
  return new Promise((resolve, reject) => {
    if(req.method !== 'POST') {
      resolve({})
      return
    }
    if(req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }

    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if(!postData) {
        resolve({})
        return
      }

      let data = {}
      try{
        data = JSON.parse(postData)
      } catch(err) {
        console.log('postData 解析失败')
      }
      resolve(data)
    })
  })
}

// // 全局session数据
// const SESSION_DATA = {}

const serverHandle = async (req, res) => {

  // 记录 access log
  accessLog(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`)

  // 设置返回格式为JSON
  res.setHeader('Content-type', 'application/json')


  // 获取path
  const url = req.url
  req.path = url.split('?')[0]


  // 解析query
  req.query = querystring.parse(url.split('?')[1])


  // 解析cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ''
  cookieStr.split('; ').forEach(item => {
    const arr = item.split('=')
    req.cookie[arr[0]] = arr[1]
  })

  console.log('req.cookie', req.cookie)

  // // 设置session
  // let needSetCookie = false
  // let userId = req.cookie.userid
  // console.log('SESSION_DATA[userId]', userId, SESSION_DATA[userId])
  // if (!userId) {
  //   needSetCookie = true
  //   userId = `${Date.now()}_${Math.random()}`
  // }

  // if (!SESSION_DATA[userId]) {
  //   SESSION_DATA[userId] = {}
  // }
  
  // req.session = SESSION_DATA[userId]


  // 设置session （使用redis）
  let needSetCookie = false
  let userId = req.cookie.userid
  if (!userId) {
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    // 初始化 redis 中的 session 值
    redis.set(userId, {})
  }
  
  // 获取session
  req.sessionId = userId
  const sessionData = await redis.get(userId) || {}
  console.log('sessionData', sessionData)
  req.session = sessionData

  // 处理post数据
  req.body = await getPostData(req)

  // 处理博客路由
  const blogResult = handleBlogRouter(req, res)
  if (blogResult) {
    blogResult.then(response => {
      console.log('response',typeof response, response)
      if (needSetCookie){
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }

      if (response) {
        res.end(JSON.stringify(response))
      }
    }).catch(err => {
      console.error('handleBlogRouter', err)
    })
    return
  }
  
  
  
  // 处理用户路由
  const userData = handleUserRouter(req, res)
  if (userData) {
    userData.then(response => {
      console.log('response',typeof response, response)

      if (needSetCookie){
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }
      
      if (response) {
        res.end(JSON.stringify(response))
      }
    }).catch(err => {
      console.error('handleUserRouter', err)
    })
    return
  }

  // 未命中路由，返回404
  res.writeHead(404, {"Content-type": "text/plain"})
  res.write("404 Not Found\n")
  res.end()

}

module.exports = serverHandle